package com.seari.custody.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaWebTokenUtil {

	private static Logger logger = LoggerFactory.getLogger(JavaWebTokenUtil.class);

	/**
	 * 解析jwt
	 */
	public static Claims parseJWT(String jsonWebToken, String base64Security) {
		try {
			Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Security)).parseClaimsJws(jsonWebToken).getBody();
			return claims;
		} catch (Exception ex) {
			logger.error("Jwt valid failed.", ex);
			return null;
		}
	}

	/**
	 * 构建jwt
	 */
	public static String createJWT(String userId, String url, long TTLMillis, String base64Security) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);

		// 生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

		// 添加构成JWT的参数
		JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT").claim("userId", userId).claim("url", url).signWith(signatureAlgorithm, signingKey);
		// 添加Token过期时间
		if (TTLMillis >= 0) {
			long expMillis = nowMillis + TTLMillis;
			Date exp = new Date(expMillis);
			// builder.setExpiration(exp).setNotBefore(now);
			builder.setExpiration(exp);
		}

		// 生成JWT
		return builder.compact();
	}
	
	/**
	 * 构建jwt
	 */
	public static String createJWT(String userId,String appId, String url, long TTLMillis, String base64Security) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);

		// 生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

		// 添加构成JWT的参数
		JwtBuilder builder = Jwts.builder().setHeaderParam("type", "JWT").claim("userId", userId).claim("appId", appId).claim("url", url).signWith(signatureAlgorithm, signingKey);
		// 添加Token过期时间
		if (TTLMillis >= 0) {
			long expMillis = nowMillis + TTLMillis;
			Date exp = new Date(expMillis);
			// builder.setExpiration(exp).setNotBefore(now);
			builder.setExpiration(exp);
		}

		// 生成JWT
		return builder.compact();
	}

	public static void main(String[] args) {
		String s = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJ1c2VySWQiOiJhZG1pbiIsInVybCI6Imh0dHA6MTI3LjAuMC4xOjgwODAvTU1TT0EiLCJleHAiOjE2MzA5OTYzMTZ9.rsXuADIzPA95pgmrgKvQQJMmcEdU0fUKd_QSnQZCInc";

		Claims claims = parseJWT(s, "JOVENOLY2018");

		String userId = claims.get("userId",String.class);
		System.out.println(userId);




	}
}
